package com.mrzhou.gateway.dynamic;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * 动态路由监听器
 * @author qiang.zhou
 * @deprecated 目前不在采用此方式设值 现使用com.mrzhou.gateway.filter.RequestFilter设置路由配置
 */
@Order
@Slf4j
@Component
@Deprecated
public class DynamicRouteListener {

    private final DynamicRouteService dynamicRouteService;
    private final NacosDiscoveryProperties nacosDiscoveryProperties;
    private final NacosConfigProperties nacosConfigProperties;

    public DynamicRouteListener(DynamicRouteService dynamicRouteService, NacosDiscoveryProperties nacosDiscoveryProperties, NacosConfigProperties nacosConfigProperties) {
        this.dynamicRouteService = dynamicRouteService;
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        this.nacosConfigProperties = nacosConfigProperties;
        dynamicRouteServiceListener();
    }

    /**
     * 监听Nacos下发的动态路由配置
     */
    protected void dynamicRouteServiceListener() {
        try{
            String dataId = "cloud-route.json"; // 需要读取哪个配置文件中的路由配置, 可以通过配置文件配置, 这里直接写死
            String group = nacosConfigProperties.getGroup(); // 配置文件所在的组, 这里默认是DEFAULT_GROUP
            String serverAddr = nacosDiscoveryProperties.getServerAddr(); // 获取nacos的服务器地址
            ConfigService configService = NacosFactory.createConfigService(serverAddr);
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String s) {
                    List<RouteDefinition> routeDefinitions = JSON.parseArray(s, RouteDefinition.class);
                    dynamicRouteService.updateList(routeDefinitions);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            String configInfo = configService.getConfig(dataId, group, 5000);
            if (configInfo != null) {
                List<RouteDefinition> routeDefinitions = JSON.parseArray(configInfo, RouteDefinition.class);
                dynamicRouteService.updateList(routeDefinitions);
            }
        } catch (NacosException ignore) {

        }
    }


}
